package com.museum.controller;

import com.museum.common.Result;
import com.museum.entity.Admin;
import com.museum.entity.SystemSettings;
import com.museum.service.AdminService;
import com.museum.service.SystemSettingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.springframework.jdbc.core.JdbcTemplate;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    
    @Autowired
    private SystemSettingsService systemSettingsService;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {
        // 验证用户名和密码
        Admin admin = adminService.login(username, password);
        if (admin == null) {
            return Result.error("用户名或密码错误");
        }
        
        // 生成token (简化版，实际项目可使用JWT)
        String token = UUID.randomUUID().toString();
        
        // 返回管理员信息和token
        Map<String, Object> data = new HashMap<>();
        data.put("id", admin.getId());
        data.put("username", admin.getUsername());
        data.put("role", admin.getRole());
        data.put("token", token);
        
        return Result.success(data);
    }

    @GetMapping("/list")
    public Result<List<Admin>> list() {
        List<Admin> adminList = adminService.list();
        // 防止密码泄露
        adminList.forEach(admin -> admin.setPassword(null));
        return Result.success(adminList);
    }
    
    @PostMapping("/add")
    public Result<Admin> add(@RequestBody Admin admin) {
        // 检查用户名是否已存在
        Admin existAdmin = adminService.lambdaQuery().eq(Admin::getUsername, admin.getUsername()).one();
        if (existAdmin != null) {
            return Result.error("用户名已存在");
        }
        
        admin.setCreateTime(LocalDateTime.now());
        admin.setUpdateTime(LocalDateTime.now());
        adminService.save(admin);
        
        // 防止密码泄露
        admin.setPassword(null);
        return Result.success(admin);
    }
    
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        // 不允许删除admin账号
        Admin admin = adminService.getById(id);
        if (admin == null) {
            return Result.error("管理员不存在");
        }
        
        if ("admin".equals(admin.getUsername())) {
            return Result.error("不能删除超级管理员");
        }
        
        boolean success = adminService.removeById(id);
        if (!success) {
            return Result.error("删除失败");
        }
        return Result.success(true);
    }
    
    @PutMapping("/reset-password/{id}")
    public Result<Map<String, String>> resetPassword(@PathVariable Long id) {
        Admin admin = adminService.getById(id);
        if (admin == null) {
            return Result.error("管理员不存在");
        }
        
        // 生成随机密码
        String newPassword = UUID.randomUUID().toString().substring(0, 8);
        admin.setPassword(newPassword);
        admin.setUpdateTime(LocalDateTime.now());
        
        adminService.updateById(admin);
        
        Map<String, String> data = new HashMap<>();
        data.put("password", newPassword);
        return Result.success(data);
    }
    
    @GetMapping("/system/settings")
    public Result<Map<String, Object>> getSystemSettings() {
        try {
        SystemSettings settings = systemSettingsService.getSettings();
        
        // 将驼峰命名转为下划线命名，以符合前端期望
        Map<String, Object> result = new HashMap<>();
        result.put("id", settings.getId());
        result.put("museum_name", settings.getMuseumName());
        result.put("open_time", settings.getOpenTime());
        result.put("contact_phone", settings.getContactPhone());
        result.put("address", settings.getAddress());
        result.put("max_reservation", settings.getMaxReservation());
        result.put("create_time", settings.getCreateTime());
        result.put("update_time", settings.getUpdateTime());
        
        return Result.success(result);
        } catch (Exception e) {
            // 添加错误日志
            e.printStackTrace();
            return Result.error("获取系统设置失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/system/settings")
    public Result<Boolean> updateSystemSettings(@RequestBody Map<String, Object> settingsMap) {
        try {
            // 获取原有设置，用于比较max_reservation是否有变化
            SystemSettings oldSettings = systemSettingsService.getSettings();
            Integer oldMaxReservation = oldSettings.getMaxReservation();
            
        SystemSettings settings = new SystemSettings();
        
        // 如果有ID则设置
        if (settingsMap.containsKey("id")) {
            settings.setId(Long.valueOf(settingsMap.get("id").toString()));
            } else {
                settings.setId(oldSettings.getId());
        }
        
        // 从下划线命名映射到驼峰命名
        if (settingsMap.containsKey("museum_name")) {
            settings.setMuseumName(settingsMap.get("museum_name").toString());
        }
        
        if (settingsMap.containsKey("open_time")) {
            settings.setOpenTime(settingsMap.get("open_time").toString());
        }
        
        if (settingsMap.containsKey("contact_phone")) {
            settings.setContactPhone(settingsMap.get("contact_phone").toString());
        }
        
        if (settingsMap.containsKey("address")) {
            settings.setAddress(settingsMap.get("address").toString());
        }
        
            // 处理最大预约数量的更新
            Integer newMaxReservation = null;
        if (settingsMap.containsKey("max_reservation")) {
                newMaxReservation = Integer.valueOf(settingsMap.get("max_reservation").toString());
                settings.setMaxReservation(newMaxReservation);
        }
        
            // 更新系统设置
        boolean success = systemSettingsService.updateSettings(settings);
        if (!success) {
            return Result.error("更新失败");
        }
            
            // 如果最大预约数变化了，更新所有未来日期的票数记录
            if (newMaxReservation != null && !newMaxReservation.equals(oldMaxReservation)) {
                // 从当前日期开始，获取未来30天内所有已存在的票务记录
                updateFutureTicketsMaximum(newMaxReservation);
            }
            
        return Result.success(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新系统设置失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新未来日期的最大票数
     * @param newMaxReservation 新的最大预约数
     */
    private void updateFutureTicketsMaximum(Integer newMaxReservation) {
        try {
            // 获取当前日期
            LocalDate today = LocalDate.now();
            String todayStr = today.format(DateTimeFormatter.ISO_LOCAL_DATE);
            
            // 批量更新未来日期的最大票数
            int updatedCount = jdbcTemplate.update(
                "UPDATE ticket_daily SET total_tickets = ?, update_time = NOW() WHERE date >= ?",
                newMaxReservation, todayStr);
            
            System.out.println("已更新 " + updatedCount + " 条未来日期的票数记录");
        } catch (Exception e) {
            System.err.println("更新未来日期票数失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 